import io
import json
import logging
import os
import re
import threading
import time
from concurrent.futures._base import Future, CancelledError
from concurrent.futures.thread import ThreadPoolExecutor

from config import envConfig
from lib import itchat
from lib.itchat.content import TEXT, VOICE, PICTURE, NOTE, ATTACHMENT
from tools import get_appdata_dir, Dequeue, remove_markdown_symbol, check_prefix, compose_attachment_name, \
    parse_file_reply
from wechat.chat_message import WechatMessage, ChatMessage
from wechat.context import ContextType, Context
from wechat.expired_dict import ExpiredDict
from wechat.reply import Reply, ReplyType, get_reply_from_backend

logger = logging.getLogger(__name__)

handler_pool = ThreadPoolExecutor(max_workers=8)


def singleton(cls):
    instances = {}

    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]

    return get_instance


# 可用的二维码生成接口
# https://api.qrserver.com/v1/create-qr-code/?size=400×400&data=https://www.abc.com
# https://api.isoyu.com/qr/?m=1&e=L&p=20&url=https://www.abc.com
def qrCallback(uuid, status, qrcode):
    logger.info("qrCallback: {} {}".format(uuid, status))
    if status == "0":
        try:
            from PIL import Image

            img = Image.open(io.BytesIO(qrcode))
            _thread = threading.Thread(target=img.show, args=("QRCode",))
            _thread.setDaemon(True)
            _thread.start()
        except Exception as e:
            pass

        import qrcode

        url = f"https://login.weixin.qq.com/l/{uuid}"

        qr_api1 = "https://api.isoyu.com/qr/?m=1&e=L&p=20&url={}".format(url)
        qr_api2 = "https://api.qrserver.com/v1/create-qr-code/?size=400×400&data={}".format(url)
        qr_api3 = "https://api.pwmqr.com/qrcode/create/?url={}".format(url)
        qr_api4 = "https://my.tv.sohu.com/user/a/wvideo/getQRCode.do?text={}".format(url)
        print("You can also scan QRCode in any website below:")
        print(qr_api3)
        print(qr_api4)
        print(qr_api2)
        print(qr_api1)
        # _send_qr_code([qr_api3, qr_api4, qr_api2, qr_api1])
        qr = qrcode.QRCode(border=1)
        qr.add_data(url)
        qr.make(fit=True)
        try:
            qr.print_ascii(invert=True)
        except UnicodeEncodeError:
            print("ASCII QR code printing failed due to encoding issues.")


@itchat.msg_register([TEXT, PICTURE, NOTE, ATTACHMENT])
def handler_single_msg(msg):
    try:
        cmsg = WechatMessage(msg, False)
    except NotImplementedError as e:
        logger.debug("[WX]single message {} skipped: {}".format(msg["MsgId"], e))
        return None
    WechatChannel().handle_single(cmsg)
    return None


@itchat.msg_register([TEXT, PICTURE, NOTE, ATTACHMENT], isGroupChat=True)
def handler_group_msg(msg):
    try:
        cmsg = WechatMessage(msg, True)
    except NotImplementedError as e:
        logger.debug("[WX]group message {} skipped: {}".format(msg["MsgId"], e))
        return None
    WechatChannel().handle_group(cmsg)
    return None


def _check(func):
    def wrapper(self, cmsg: ChatMessage):
        msgId = cmsg.msg_id
        if msgId in self.receivedMsgs:
            logger.info("[WX] Wechat message {} already received, ignore".format(msgId))
            return
        self.receivedMsgs[msgId] = True
        create_time = cmsg.create_time  # 消息时间戳
        if envConfig.HOT_RELOAD is True and int(create_time) < int(time.time()) - 60:  # 跳过1分钟前的历史消息
            logger.info("[WX] history message {} skipped".format(cmsg))
            return
        if cmsg.my_msg and not cmsg.is_group:
            logger.info("[WX] my message {} skipped".format(msgId))
            return
        return func(self, cmsg)

    return wrapper

    # 统一的发送函数，每个Channel自行实现，根据reply的type字段发送不同类型的消息


@singleton
class WechatChannel:
    NOT_SUPPORT_REPLYTYPE = [ReplyType.VOICE, ReplyType.IMAGE]

    name = None  # 登录的用户名
    user_id = None  # 登录的用户id
    futures = {}  # 记录每个session_id提交到线程池的future对象, 用于重置会话时把没执行的future取消掉，正在执行的不会被取消
    sessions = {}  # 用于控制并发，每个session_id同时只能有一个context在处理
    lock = threading.Lock()  # 用于控制对sessions的访问

    def __init__(self):
        self.auto_login_times = 0
        self.receivedMsgs = ExpiredDict(envConfig.EXPIRED_IN_SECONDS)
        _thread = threading.Thread(target=self.consume)
        _thread.setDaemon(True)
        _thread.start()

    def startup(self):
        try:
            itchat.instance.receivingRetryCount = 600  # 修改断线超时时间
            # login by scan QRCode
            hotReload = envConfig.HOT_RELOAD
            status_path = os.path.join(get_appdata_dir(), "itchat.pkl")
            itchat.auto_login(
                enableCmdQR=2,
                hotReload=hotReload,
                statusStorageDir=status_path,
                qrCallback=qrCallback,
                exitCallback=self.exitCallback,
                loginCallback=self.loginCallback
            )
            self.user_id = itchat.instance.storageClass.userName
            self.name = itchat.instance.storageClass.nickName
            logger.info("[INIT] Wechat login success, user_id: {}, nickname: {}".format(self.user_id, self.name))
            # start message listener
            itchat.run()
        except Exception as e:
            logger.exception(e)

    def exitCallback(self):
        try:
            time.sleep(2)
            self.auto_login_times += 1
            if self.auto_login_times < 100:
                handler_pool._shutdown = False
                self.startup()
        except Exception as e:
            logger.error("[WX] Trying to restart failed.")
            logger.exception(e)

    def loginCallback(self):
        logger.info("[WX]Login success")
        # _send_login_success()

    @_check
    def handle_single(self, cmsg: ChatMessage):
        # filter system message
        if cmsg.other_user_id in ["weixin"]:
            return
        if cmsg.ctype == ContextType.VOICE:
            logger.info("[WX IGNORED] Voice information will be ignored, from{}".format(cmsg.from_user_id))
            return
        elif cmsg.ctype == ContextType.IMAGE:
            logger.info("[WX]receive image msg, will be ignored, from {}".format(cmsg.from_user_id))
        elif cmsg.ctype == ContextType.PATPAT:
            logger.info("[WX]receive patpat msg: {}".format(cmsg.content))
        elif cmsg.ctype == ContextType.TEXT:
            logger.info("[WX]receive text msg: {}, cmsg={}".format(json.dumps(cmsg._rawmsg, ensure_ascii=False), cmsg))
        else:
            logger.info("[WX]receive msg: {}, cmsg={}".format(cmsg.content, cmsg))
        context = self._compose_context(cmsg.ctype, cmsg.content, isgroup=False, msg=cmsg)
        if context:
            self.produce(context)

    @_check
    def handle_group(self, cmsg: ChatMessage):
        if cmsg.ctype == ContextType.VOICE:
            logger.info("[WX IGNORED] Voice information will be ignored, from{}".format(cmsg.from_user_id))
            return
        elif cmsg.ctype == ContextType.IMAGE:
            logger.info("[WX]receive image for group msg: {}".format(cmsg.content))
        elif cmsg.ctype in [ContextType.JOIN_GROUP, ContextType.PATPAT, ContextType.ACCEPT_FRIEND,
                            ContextType.EXIT_GROUP]:
            logger.info("[WX]receive note msg: {}".format(cmsg.content))
        elif cmsg.ctype == ContextType.TEXT:
            logger.info("[WX]receive group msg: {}, cmsg={}".format(json.dumps(cmsg._rawmsg, ensure_ascii=False), cmsg))
            # pass
        elif cmsg.ctype == ContextType.FILE:
            logger.info(f"[WX]receive attachment msg, file_name={cmsg.content}")
        else:
            logger.info("[WX]receive group msg: {}".format(cmsg.content))
        context = self._compose_context(cmsg.ctype, cmsg.content, isgroup=True, msg=cmsg,
                                        no_need_at=envConfig.NO_NEED_AT)
        if context:
            self.produce(context)

    def _compose_context(self, ctype: ContextType, content, **kwargs):
        context = Context(ctype, content)
        context.kwargs = kwargs
        # context首次传入时，origin_ctype是None,
        # 引入的起因是：当输入语音时，会嵌套生成两个context，第一步语音转文本，第二步通过文本生成文字回复。
        # origin_ctype用于第二步文本回复时，判断是否需要匹配前缀，如果是私聊的语音，就不需要匹配前缀
        if "origin_ctype" not in context:
            context["origin_ctype"] = ctype
        # context首次传入时，receiver是None，根据类型设置receiver
        first_in = "receiver" not in context
        if first_in:
            cmsg = context["msg"]
            if context.get("is_group", False):
                group_name = cmsg.other_user_nickname
                group_id = cmsg.other_user_id
                group_name_white_list = envConfig.GROUP_NAME_WHITE_LIST

                if any([group_name in group_name_white_list,
                        "ALL_GROUP" in group_name_white_list]):
                    session_id = cmsg.actual_user_id
                    group_chat_in_one_session = []  # 不太清楚这个是干嘛的，先抄下来
                    # group_chat_in_one_session = conf().get("group_chat_in_one_session", [])
                    if any(
                            [
                                group_name in group_chat_in_one_session,
                                "ALL_GROUP" in group_chat_in_one_session,
                            ]
                    ):
                        session_id = group_id
                else:
                    logger.debug(f"[WX IGNORED]No need reply, groupName not in whitelist, group_name={group_name}")
                    return None
                context["session_id"] = session_id
                context["receiver"] = group_id
            else:
                context["session_id"] = cmsg.other_user_id
                context["receiver"] = cmsg.other_user_id
            # Plugin 暂时不需要
            # e_context = PluginManager().emit_event(EventContext(Event.ON_RECEIVE_MESSAGE, {"channel": self, "context": context}))
            # context = e_context["context"]
            if context is None:
                return context
            if cmsg.from_user_id == self.user_id:
                logger.debug("[chat_channel]self message skipped")
                return None

        # 消息内容匹配过程，并处理content
        if ctype.compare(ContextType.TEXT):
            # 引用句式类似于：「慌雨：[文件]XXXX.xls」\n- - - - - - - - - - - - - - -\n金桔王呢？ 这样无法匹配机器人的触发，需要倒过来
            if "」\n- - - - - - -" in content:
                updated_refs = content.split("\n")
                content = ' '.join(sorted(updated_refs, key=lambda x: (len(x), x)))
                logger.info(f"[chat_channel] Received reference message, reverse it to {context}.")
            # if first_in:  # 初次匹配
            #     logger.info(content)
            #     logger.info("[chat_channel]First in and reference query received, skipped")
            #     return None

            # nick_name_black_list = conf().get("nick_name_black_list", [])
            if context.get("isgroup", False):  # 群聊
                # 校验关键字
                match_prefix = check_prefix(content, envConfig.GROUP_CHAT_PREFIX)
                # match_contain = check_contain(content, conf().get("group_chat_keyword"))  # 群聊时包含该关键词则会触发机器人回复, 好像不需要
                flag = False
                if context["msg"].to_user_id != context["msg"].actual_user_id:
                    if match_prefix is not None:
                        flag = True
                        if match_prefix:
                            content = content.replace(match_prefix, "", 1).strip()
                    if context["msg"].is_at:
                        nick_name = context["msg"].actual_user_nickname
                        if nick_name and nick_name in envConfig.NICK_NAME_BLACK_LIST:
                            # 黑名单过滤
                            logger.warning(f"[chat_channel] Nickname {nick_name} in In BlackList, ignore")
                            return None

                        logger.info("[chat_channel]receive group at")
                        # if not conf().get("group_at_off", False):  # 是否关闭群聊时@bot的触发, 这里不需要
                        #     flag = True
                        self.name = self.name if self.name is not None else ""  # 部分渠道self.name可能没有赋值
                        pattern = f"@{re.escape(self.name)}(\u2005|\u0020)"
                        subtract_res = re.sub(pattern, r"", content)
                        if isinstance(context["msg"].at_list, list):
                            for at in context["msg"].at_list:
                                pattern = f"@{re.escape(at)}(\u2005|\u0020)"
                                subtract_res = re.sub(pattern, r"", subtract_res)
                        if subtract_res == content and context["msg"].self_display_name:
                            # 前缀移除后没有变化，使用群昵称再次移除
                            pattern = f"@{re.escape(context['msg'].self_display_name)}(\u2005|\u0020)"
                            subtract_res = re.sub(pattern, r"", content)
                        content = subtract_res
                if not flag:
                    if context["origin_ctype"] == ContextType.VOICE:
                        logger.info("[chat_channel]receive group voice, but checkprefix didn't match")
                    return None
            else:  # 单聊
                nick_name = context["msg"].from_user_nickname
                if nick_name and nick_name in envConfig.NICK_NAME_BLACK_LIST:
                    # 黑名单过滤
                    logger.warning(f"[chat_channel] Nickname '{nick_name}' in In BlackList, ignore")
                    return None

                match_prefix = check_prefix(content, envConfig.SINGLE_CHAT_PREFIX)
                if match_prefix is not None:  # 判断如果匹配到自定义前缀，则返回过滤掉前缀+空格后的内容
                    content = content.replace(match_prefix, "", 1).strip()
                # elif context["origin_ctype"] == ContextType.VOICE:  # 语音忽略，不准发语音，因为广西人口音太重
                #     pass
                else:
                    return None
            content = content.strip()
            # img_match_prefix = check_prefix(content, conf().get("image_create_prefix", [""]))  画图拒绝
            # if img_match_prefix:
            #     content = content.replace(img_match_prefix, "", 1)
            #     context.type = ContextType.IMAGE_CREATE
            # else:
            context.type = ContextType.TEXT
            context.content = content.strip()
            # if "desire_rtype" not in context and conf().get(  #  只能回复文本
            #         "always_reply_voice") and ReplyType.VOICE not in self.NOT_SUPPORT_REPLYTYPE:
            #     context["desire_rtype"] = ReplyType.VOICE
        elif ctype.compare(ContextType.FILE):
            pass
        elif ctype.compare(ContextType.VOICE):
            logger.info("[chat_channel]receive voice message, ignored.")
            # if "desire_rtype" not in context and conf().get(
            #         "voice_reply_voice") and ReplyType.VOICE not in self.NOT_SUPPORT_REPLYTYPE:
            #     context["desire_rtype"] = ReplyType.VOICE
        logger.info("[chat_channel] Built context: {}".format(context))

        return context

    def _handle(self, context: Context):
        if context is None or not context.content:
            return
        logger.info("[chat_channel] ready to handle context: {}".format(context))
        # reply的构建步骤
        reply = self._generate_reply(context)

        logger.info("[chat_channel] ready to decorate reply: {}".format(reply))

        # reply的包装步骤
        if reply and reply.content:
            reply = self._decorate_reply(context, reply)
            logger.info("[chat_channel] ready to decorate reply: {}".format(reply))
            # reply的发送步骤
            self._send(reply, context)

    def _generate_reply(self, context: Context, reply: Reply = Reply()) -> Reply | None:
        # e_context = PluginManager().emit_event(
        #     EventContext(
        #         Event.ON_HANDLE_CONTEXT,
        #         {"channel": self, "context": context, "reply": reply},
        #     )
        # )
        # reply = e_context["reply"]
        # if not e_context.is_pass():
        logger.info("[chat_channel] ready to handle context: type={}, content={}".format(context.type, context.content))
        if context.type.compare(ContextType.TEXT) or context.type == ContextType.IMAGE_CREATE:  # 文字和图片消息
            # context["channel"] = e_context["channel"]
            reply = get_reply_from_backend(context)  # TODO: 转发到我的服务器
        elif context.type == ContextType.VOICE:  # 语音消息， 忽略
            pass
        #     cmsg = context["msg"]
        #     cmsg.prepare()
        #     file_path = context.content
        #     wav_path = os.path.splitext(file_path)[0] + ".wav"
        #     try:
        #         any_to_wav(file_path, wav_path)
        #     except Exception as e:  # 转换失败，直接使用mp3，对于某些api，mp3也可以识别
        #         logger.warning("[chat_channel]any to wav error, use raw path. " + str(e))
        #         wav_path = file_path
        #     # 语音识别
        #     reply = super().build_voice_to_text(wav_path)
        #     # 删除临时文件
        #     try:
        #         os.remove(file_path)
        #         if wav_path != file_path:
        #             os.remove(wav_path)
        #     except Exception as e:
        #         pass
        #         # logger.warning("[chat_channel]delete temp file error: " + str(e))
        #
        #     if reply.type == ReplyType.TEXT:
        #         new_context = self._compose_context(ContextType.TEXT, reply.content, **context.kwargs)
        #         if new_context:
        #             reply = self._generate_reply(new_context)
        #         else:
        #             return
        # elif context.type == ContextType.IMAGE:  # 图片消息，当前仅做下载保存到本地的逻辑
        #     memory.USER_IMAGE_CACHE[context["session_id"]] = {
        #         "path": context.content,
        #         "msg": context.get("msg")
        #     }
        elif context.type == ContextType.SHARING:  # 分享信息，当前无默认逻辑
            pass
        elif context.type.compare(ContextType.FILE):  # 文件消息及函数调用等，当前无默认逻辑

            cmsg = context["msg"]
            new_filepath = compose_attachment_name(cmsg.is_group, cmsg.actual_user_nickname,
                                                   cmsg.from_user_nickname, cmsg.content)
            logger.info(f"[file] Composed file name as {new_filepath}")
            if os.path.exists(new_filepath):
                reply = Reply(ReplyType.TEXT, f"这个文件名重复了，如果需要导入的话，请重命名：{cmsg.content}，\n 如果不需要导入就忽略这条信息噢~")
            elif not new_filepath.split('.')[-1] in envConfig.ACCEPT_FILE_TYPE:
                logger.info(f"[file] File type not supported: {cmsg.content}, skipped.")
                return
            else:
                cmsg.content = new_filepath
                context.content = new_filepath
                context['msg'].prepare()
                if os.path.exists(cmsg.content):
                    context.content = envConfig.CHECKSUM_KEYS + context.content
                    context['msg'].content = envConfig.CHECKSUM_KEYS + context.content
                    logger.info(f"[file] Ask checksum from backend for {context.content}")
                    reply = get_reply_from_backend(context)
                    if reply.content == 'SKIP':
                        logger.info("[file] File removed, which is not expected format.")
                        return
                    logger.info("[chat_channel] ready to handle File context: type={}, content={}"
                                .format(context.type, context.content))
                else:
                    reply = Reply(ReplyType.ERROR, f"这个文件存不了啊，找我爹看看~")
                    logger.error("[file] Saving file failed...unknown reason."
                                 "ready to handle File context: type={}, content={}"
                                 .format(context.type, context.content))
                logger.warning("[file] File exists! ready to handle context: type={}, content={}"
                               .format(context.type, context.content))
        else:
            logger.warning("[chat_channel] unknown context type: {}".format(context.type))
            return
        return reply

    def _decorate_reply(self, context: Context, reply: Reply) -> Reply:
        desire_rtype = context.get("desire_rtype")
        if desire_rtype is None:
            desire_rtype = reply.type

        if reply.type == ReplyType.TEXT:
            reply_text = reply.content
            # if desire_rtype == ReplyType.VOICE and ReplyType.VOICE not in self.NOT_SUPPORT_REPLYTYPE:  # Voice skipped
            #     reply = super().build_text_to_voice(reply.content)
            #     return self._decorate_reply(context, reply)
            if context.get("isgroup", False):
                if not context.get("no_need_at", False):
                    reply_text = "@" + context["msg"].actual_user_nickname + "\n" + reply_text.strip()
                reply_text = envConfig.GROUP_CHAT_REPLY_PREFIX + reply_text + envConfig.GROUP_CHAT_REPLY_SUFFIX
            else:
                reply_text = envConfig.SINGLE_CHAT_REPLY_PREFIX + reply_text + envConfig.SINGLE_CHAT_REPLY_SUFFIX
            reply.content = reply_text
        elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
            reply.content = "[" + str(reply.type) + "]\n" + reply.content
        elif reply.type == ReplyType.IMAGE_URL or reply.type == ReplyType.VOICE or reply.type == ReplyType.IMAGE or \
                reply.type == ReplyType.FILE or reply.type == ReplyType.VIDEO or reply.type == ReplyType.VIDEO_URL:
            pass
        else:
            logger.error("[chat_channel] unknown reply type: {}".format(reply.type))
            return
        if desire_rtype and desire_rtype != reply.type and reply.type not in [ReplyType.ERROR, ReplyType.INFO]:
            logger.warning("[chat_channel] desire_rtype: {}, but reply type: {}"
                           .format(context.get("desire_rtype"), reply.type))
        return reply

    def _send(self, reply: Reply, context: Context, retry_cnt=0):
        try:
            self.send(reply, context)
        except Exception as e:
            logger.error("[chat_channel] sendMsg error: {}".format(str(e)))
            logger.exception(e)
            if retry_cnt < 2:
                time.sleep(3 + 3 * retry_cnt)
                self._send(reply, context, retry_cnt + 1)

    def produce(self, context: Context):
        session_id = context["session_id"]
        with self.lock:
            if session_id not in self.sessions:
                self.sessions[session_id] = [
                    Dequeue(),
                    threading.BoundedSemaphore(envConfig.CONCURRENCY_IN_SESSION),
                ]
            if context.type == ContextType.TEXT and context.content.startswith("#"):
                self.sessions[session_id][0].putleft(context)  # 优先处理管理命令
            else:
                self.sessions[session_id][0].put(context)

    def consume(self):
        while True:
            with self.lock:
                session_ids = list(self.sessions.keys())
            for session_id in session_ids:
                with self.lock:
                    context_queue, semaphore = self.sessions[session_id]
                if semaphore.acquire(blocking=False):  # 等线程处理完毕才能删除
                    if not context_queue.empty():
                        context = context_queue.get()
                        logger.info("[chat_channel] consume context: {}".format(context))
                        future: Future = handler_pool.submit(self._handle, context)
                        future.add_done_callback(self._thread_pool_callback(session_id, context=context))
                        with self.lock:
                            if session_id not in self.futures:
                                self.futures[session_id] = []
                            self.futures[session_id].append(future)
                    elif semaphore._initial_value == semaphore._value + 1:  # 除了当前，没有任务再申请到信号量，说明所有任务都处理完毕
                        with self.lock:
                            self.futures[session_id] = [t for t in self.futures[session_id] if not t.done()]
                            assert len(self.futures[session_id]) == 0, "thread pool error"
                            del self.sessions[session_id]
                    else:
                        semaphore.release()
            time.sleep(0.2)

    def send(self, reply: Reply, context: Context):
        receiver = context["receiver"]
        if reply.type == ReplyType.SKIP:
            return
        if reply.type == ReplyType.TEXT:
            reply.content = remove_markdown_symbol(reply.content)
            itchat.send(reply.content, toUserName=receiver)
            logger.info("[WX] sendMsg={}, receiver={}".format(reply, receiver))
        elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
            reply.content = remove_markdown_symbol(reply.content)
            itchat.send(reply.content, toUserName=receiver)
            logger.info("[WX] sendMsg={}, receiver={}".format(reply, receiver))
        elif reply.type == ReplyType.VOICE:
            pass  # 没有语音
            # itchat.send_file(reply.content, toUserName=receiver)
            # logger.info("[WX] sendFile={}, receiver={}".format(reply.content, receiver))
        elif reply.type == ReplyType.IMAGE_URL:  # 从网络下载图片，没有图片连接
            logger.info("[WX] Ignored this sendImage url={}, receiver={}".format(reply.content, receiver))
            # img_url = reply.content
            # logger.debug(f"[WX] start download image, img_url={img_url}")
            # pic_res = requests.get(img_url, stream=True)
            # image_storage = io.BytesIO()
            # size = 0
            # for block in pic_res.iter_content(1024):
            #     size += len(block)
            #     image_storage.write(block)
            # logger.info(f"[WX] download image success, size={size}, img_url={img_url}")
            # image_storage.seek(0)
            # if ".webp" in img_url:
            #     try:
            #         image_storage = convert_webp_to_png(image_storage)
            #     except Exception as e:
            #         logger.error(f"Failed to convert image: {e}")
            #         return
            # itchat.send_image(image_storage, toUserName=receiver)
            # logger.info("[WX] sendImage url={}, receiver={}".format(img_url, receiver))
        elif reply.type == ReplyType.IMAGE:  # 从文件读取图片, 可能需要，没想好
            image_storage = reply.content
            image_storage.seek(0)
            itchat.send_image(image_storage, toUserName=receiver)
            logger.info("[WX] Ignored this sendImage, receiver={}".format(receiver))
        elif reply.type == ReplyType.FILE:  # 新增文件回复类型
            file_storage, text = parse_file_reply(reply.content)
            itchat.send_file(file_storage, toUserName=receiver)
            itchat.send(text, toUserName=receiver)
            logger.info("[WX] sendFile, receiver={}, file={}, text={}".format(receiver, file_storage, text))
        elif reply.type == ReplyType.VIDEO:  # 新增视频回复类型, 没有视频噢， 没有钱噢
            # video_storage = reply.content
            # itchat.send_video(video_storage, toUserName=receiver)
            logger.info("[WX] Ignored this sendFile, receiver={}".format(receiver))
        elif reply.type == ReplyType.VIDEO_URL:  # 新增视频URL回复类型， 也没有噢
            # video_url = reply.content
            # logger.debug(f"[WX] start download video, video_url={video_url}")
            # video_res = requests.get(video_url, stream=True)
            # video_storage = io.BytesIO()
            # size = 0
            # for block in video_res.iter_content(1024):
            #     size += len(block)
            #     video_storage.write(block)
            # logger.info(f"[WX] download video success, size={size}, video_url={video_url}")
            # video_storage.seek(0)
            # itchat.send_video(video_storage, toUserName=receiver)
            logger.info("[WX] Ignored this sendVideo receiver={}".format(receiver))

    def _thread_pool_callback(self, session_id, **kwargs):
        def func(worker: Future):
            try:
                worker_exception = worker.exception()
                if worker_exception:
                    self._fail_callback(session_id, exception=worker_exception, **kwargs)
                else:
                    self._success_callback(session_id, **kwargs)
            except CancelledError as e:
                logger.info("Worker cancelled, session_id = {}".format(session_id))
            except Exception as e:
                logger.exception("Worker raise exception: {}".format(e))
            with self.lock:
                self.sessions[session_id][1].release()

        return func

    def _fail_callback(self, session_id, exception, **kwargs):  # 线程异常结束时的回调函数
        logger.exception("Worker return exception: {} with session {}".format(exception, session_id))

    def _success_callback(self, session_id, **kwargs):  # 线程正常结束时的回调函数
        logger.debug("Worker return success, session_id = {}".format(session_id))
